import React, { useEffect, useMemo, useState } from "react";
import { modalPropsType } from "@/constants/types";
import { Modal, Form, Space, Button, Image } from "antd";
import XlSelect from "@/components/Form/XlSelect";
import { MinusOutlined, PlusOutlined } from "@ant-design/icons";
import { fetchAdAdSlot, fetchAdPageOptions } from "../../services";
import { useComponentDidMount } from "@/hooks";

const { Item } = Form;

const AdBindPosition = ({visible, onCancel, onSubmit, currentRow, title}: modalPropsType) => {
  const [form] = Form.useForm();
  const [pages, setPages] = useState([]);

  const adBinds = Form.useWatch("adBinds", form);

  const handleSubmit = async () => {
    const res = await form.validateFields();
    onSubmit({
      id: currentRow?.id,
      adBinds: res?.adBinds || []
    });
  }


  const previewImgs = useMemo(() => {
    return pages?.filter((v: any) => adBinds.some((d: any) => d.pageId === v.id))?.map((s: any) => s.imageUrl) || [];
  }, [JSON.stringify(adBinds), JSON.stringify(pages)]);

  useEffect(() => {
    if (currentRow?.id) {
      fetchAdAdSlot({adId: currentRow?.id}).then(
        res => {
          form.setFieldsValue({
            adBinds: res?.data?.length > 0 ? res?.data : [{}]
          });
        }
      );
    }
  }, [currentRow?.id]);

  useComponentDidMount(() => {
    fetchAdPageOptions().then(
      res => {
        setPages(res || []);
      }
    )
  });

  return (
    <Modal
      title={title}
      onCancel={onCancel}
      open={visible}
      onOk={handleSubmit}
      width="700px"
      maskClosable={false}
    >
      <Form form={form} className="modal-form-padding">
        <Item label="广告位" required>
          <Form.List name="adBinds" initialValue={[{}]}>
              {(fields, {add, remove}) =>
                fields.map((field, fieldIndex) => (
                  <Space style={{marginBottom: 20}} key={field.name}>
                    <Item noStyle name={[field.name, "pageId"]} rules={[{required: true, message: '请选择广告页'}]}>
                      <XlSelect style={{width: 250}} optionFilterProp="label" onChange={() => form.setFieldValue(['adBinds', field.name, 'slot'], null)} showSearch options={pages} dataLabel="name" dataValue="id" />
                    </Item>
                    <Item noStyle shouldUpdate>
                      {({getFieldValue}) => {
                        const pageId = getFieldValue(['adBinds', field.name, 'pageId']);
                        const options = pages.find((v: any) => v.id === pageId)?.slots || [];
                        return (
                          <Item noStyle name={[field.name, "slot"]} rules={[{required: true, message: '请选择广告位'}]}>
                            <XlSelect style={{width: 250}} optionFilterProp="label" showSearch options={options?.map((v: string) => ({label: v, value: v}))} />
                          </Item>
                        );
                      }}
                    </Item>
                    {fieldIndex === 0 && <Button type="primary" onClick={() => add({})}><PlusOutlined /></Button>}
                    {fieldIndex > 0 && <Button type="primary" onClick={() => remove(field.name)}><MinusOutlined /></Button>}
                  </Space>
                ))
              }
            </Form.List>
        </Item>
      </Form>
      <div style={{display: 'flex', justifyContent: 'center', marginTop: 20}}>
        <Image.PreviewGroup
          preview={{
            onChange: (current, prev) => console.log(`current index: ${current}, prev index: ${prev}`),
          }}
        >
          {previewImgs?.map((v: string) => (
            <Image key={v} width={250} style={{marginRight: 30}} src={v} />
          ))}
        </Image.PreviewGroup>
      </div>
    </Modal>
  );
}
export default AdBindPosition;